<html>
<head><title>Web Socket Test</title></head>
<body>
<form onsubmit="return false;">

    <input type="button" value="注册推送"
           onclick="send()"/>
    <input type="button" value="关闭聊天"
           onclick="socket.close()"/>
    <h3>Output</h3>
    <textarea id="responseText" style="width:500px;height:300px;"></textarea>
</form>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">

    var socket;
    if (!window.WebSocket) {
        window.WebSocket = window.MozWebSocket;
    }
    if (window.WebSocket) {
        socket = new WebSocket("ws://127.0.0.1:8858/pushProxy");
        var h_resp;
        var heartCheck = {
            timeout: 5000,
            timeoutObj: null,
            serverTimeoutObj: null,
            start: function () {
                var self = this;
                this.timeoutObj && clearTimeout(this.timeoutObj);
                this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
                this.timeoutObj = setTimeout(function () {
                        console.log('heartCheck start');
                        socket.send("{\"msgType\":3}");
                        self.serverTimeoutObj = setTimeout(function () {
                            if (!h_resp) {
                                console.log('wait timeOut,close ws client');
                                socket.close();
                            } else {
                                h_resp = null;
                                heartCheck.start();
                            }
                        }, self.timeout);
                    }, this.timeout
                )
            }
        }

        socket.onmessage = function (event) {
            var ta = document.getElementById('responseText');
            ta.value = ta.value + '\n' + event.data;
            h_resp = event.data;
        };
        socket.onopen = function (event) {
            var ta = document.getElementById('responseText');
            ta.value = "Web Socket opened!";
            heartCheck.start();
        };
        socket.onclose = function (event) {
            var ta = document.getElementById('responseText');
            ta.value = ta.value + "Web Socket closed";
        };
    } else {
        alert("Your browser does not support Web Socket.");
    }
    function send() {
        if (!window.WebSocket) {
            return;
        }
        if (socket.readyState == WebSocket.OPEN) {
            var reg;
            reg = {"msgType": 0, "fromId": "android001", "pushType": 1, "appKey": "c8b1a74c11784fceb53d65f37c63439f"};
            socket.send(JSON.stringify(reg));
        } else {
            alert("The socket is not open.");
        }
    }
</script>
</body>
</html>